<template>
  <div class="design-table">
    <je-table
      ref="xTable"
      border
      auto-resize
      show-overflow="ellipsis"
      keep-source
      show-header-overflow
      :data="concernDatas.tabelData"
      resizable
      header-align="center"
      :scroll-y="{ mode: 'wheel' }"
      :edit-config="{
        trigger: 'click',
        mode: 'cell',
        showUpdateStatus: true,
        showInsertStatus: false,
      }"
    >
      <je-column :title="$t('viewModal.designView.operateCloumn')" width="40" align="center">
        <template #header>
          <i style="font-size: 16px; cursor: pointer" class="fal fa-plus" @click="addColumn"></i>
        </template>
        <template #default="{ row }">
          <i
            style="font-size: 16px; cursor: pointer"
            class="fal fa-times"
            @click="deleteColumn(row)"
          ></i>
        </template>
      </je-column>
      <je-column
        field="mainTableCode"
        :title="$t('viewModal.designView.tableACloumn')"
        :edit-render="{}"
      >
        <template #edit="{ row }">
          <je-select
            v-model:value="row.mainTableCode"
            style="width: 100%"
            @select="selectTable1(row)"
          >
            <je-select-option
              v-for="item in tableDesigndata.selectDatas"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </je-select-option>
          </je-select>
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.mainTableCode, tableDesigndata.selectDatas) }}
        </template>
      </je-column>
      <je-column
        field="mainColumn"
        :title="$t('viewModal.designView.fieldACloumn')"
        :edit-render="inputRender"
      >
        <template #edit="{ row }">
          <je-grid-select
            v-model:value="row.mainColumn"
            editable
            :select-options="{ title: '选择字段' }"
            name="mainColumn"
            config-info="JE_CORE_TABLECOLUMN,mainColumn,TABLECOLUMN_CODE,S"
            :querys="getJQuery(row, 'mainTableCode')"
            :orders="[
              { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
              { code: 'SY_ORDERINDEX', type: 'ASC' },
            ]"
          />
        </template>
      </je-column>
      <je-column field="mainIdentifier" :edit-render="{}" width="100" align="center">
        <template #header>
          <i class="conditionicon fas fa-question-circle" @click="clickIcon('mainIdentifier')"></i>
          {{ $t('viewModal.designView.identifierACloumn') }}
        </template>
        <template #edit="{ row }">
          <je-select
            v-model:value="row.mainIdentifier"
            style="width: 100%"
            @change="changeCheckbox(row)"
          >
            <je-select-option
              v-for="item in tableDesigndata.aMarkingOptions"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </je-select-option>
          </je-select>
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.mainIdentifier, tableDesigndata.aMarkingOptions) }}
        </template>
      </je-column>
      <je-column
        field="formula"
        :title="$t('viewModal.designView.formulaCloumn')"
        :edit-render="{}"
        width="150"
      >
        <template #edit="{ row }">
          <je-select v-model:value="row.formula" style="width: 100%">
            <je-select-option
              v-for="item in tableDesigndata.connOptions"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </je-select-option>
          </je-select>
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.formula, tableDesigndata.connOptions) }}
        </template>
      </je-column>
      <je-column
        field="targetTableCode"
        :title="$t('viewModal.designView.tableBCloumn')"
        :edit-render="{}"
      >
        <template #edit="{ row }">
          <je-select
            v-model:value="row.targetTableCode"
            style="width: 100%"
            @select="selectTable2(row)"
          >
            <je-select-option
              v-for="item in tableDesigndata.selectDatas"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </je-select-option>
          </je-select>
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.targetTableCode, tableDesigndata.selectDatas) }}
        </template>
      </je-column>
      <je-column
        field="targetColumn"
        :title="$t('viewModal.designView.fieldBCloumn')"
        :edit-render="inputRender"
      >
        <template #edit="{ row }">
          <je-grid-select
            v-model:value="row.targetColumn"
            editable
            name="targetColumn"
            config-info="JE_CORE_TABLECOLUMN,targetColumn,TABLECOLUMN_CODE,S"
            :querys="getJQuery(row, 'targetTableCode')"
            :orders="[
              { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
              { code: 'SY_ORDERINDEX', type: 'ASC' },
            ]"
          />
        </template>
      </je-column>
      <je-column field="targetIdentifier" :edit-render="{}" width="100" align="center">
        <template #header>
          <i
            class="conditionicon fas fa-question-circle"
            @click="clickIcon('targetIdentifier')"
          ></i>
          {{ $t('viewModal.designView.identifierBCloumn') }}
        </template>
        <template #edit="{ row }">
          <je-select
            v-model:value="row.targetIdentifier"
            style="width: 100%"
            @change="changeCheckbox(row)"
          >
            <je-select-option
              v-for="item in tableDesigndata.bMarkingOptions"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </je-select-option>
          </je-select>
        </template>
        <template #default="{ row }">
          {{ getSelectLabel(row.targetIdentifier, tableDesigndata.bMarkingOptions) }}
        </template>
      </je-column>
      <je-column field="isDispalyLine" width="80" align="center">
        <template #header>
          <i class="conditionicon fas fa-question-circle" @click="clickIcon('isDispalyLine')"></i>
          {{ $t('viewModal.designView.showCloumn') }}
        </template>
        <template #default="{ row }">
          <je-checkbox
            v-model:checked="row.isDispalyLine"
            :disabled="row.disabled"
            @change="changeCheckbox(row)"
          />
        </template>
      </je-column>
      <template #tbar>
        <div class="design-title bottom"> {{ $t('viewModal.designView.titleDesign') }} </div>
      </template>
    </je-table>
  </div>

  <je-modal
    v-model:visible="visibleCondition"
    width="400px"
    title="说明"
    height="auto"
    :resize="false"
    ok-button
    button-align="right"
    :maximizable="false"
  >
    <div>
      {{ modalText }}
    </div>
  </je-modal>
</template>

<script>
  import { defineComponent, ref, onMounted, reactive, nextTick } from 'vue';
  import { Grid, Select, Checkbox, InputSelect, Modal } from '@jecloud/ui';
  import { uuid } from '@jecloud/utils';
  import VueEvent from '../../helper/model/event';
  import { inputRender, numberRender } from '../../helper/edit-render';
  import { JE_VIEWDESIGN_SELECTOPTIONS } from '@/helper/common';

  export default defineComponent({
    name: 'ConcernView',
    components: {
      JeTable: Grid,
      JeColumn: Grid.Column,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeCheckbox: Checkbox,
      JeGridSelect: InputSelect.Grid,
      JeModal: Modal,
    },
    props: {
      concernDatas: {
        type: Object,
        requied: true,
        default: () => {
          return {};
        },
      },
      tableId: {
        type: String,
        default: '',
      },
      addTable: {
        type: Object,
        default: () => {
          return {};
        },
      },
      deaignSelected: {
        type: Object,
        requied: true,
        default: () => {
          return {};
        },
      },
    },
    emits: ['getConcernTable', 'changeLine'],
    setup(props, { emit }) {
      const xTable = ref(null);
      const pkValue = ref(props.tableId);

      onMounted(() => {
        nextTick(() => {
          emit('getConcernTable', getXTable());
        });
      });

      const tableDesigndata = reactive({
        selectDatas: props.concernDatas.selectDatas, //视图拖拽表的详细信息
        aMarkingOptions: JE_VIEWDESIGN_SELECTOPTIONS.aMarkingOptions,
        bMarkingOptions: JE_VIEWDESIGN_SELECTOPTIONS.bMarkingOptions,
        connOptions: JE_VIEWDESIGN_SELECTOPTIONS.connOptions,
      });

      //列表单元格格式化
      const getSelectLabel = (value, list, valueProp = 'value', labelField = 'label') => {
        const item = list.find((item) => item[valueProp] === value);
        return item ? item[labelField] : null;
      };

      //关系设置列表数据添加
      const addColumn = async () => {
        const $table = getXTable();
        const record = {
          id: uuid(),
          mainTableCode: '',
          mainColumn: '',
          mainIdentifier: '1',
          targetTableCode: '',
          targetColumn: '',
          targetIdentifier: '1',
          formula: '=',
          isDispalyLine: false,
          disabled: true,
          mainTableId: '',
          mainTableName: '',
          targetTableId: '',
          targetTableName: '',
        };
        await $table.insertAt(record, -1);
        //context.emit('changeDesignData', $table);
      };

      //关系设置列表数据删除
      const deleteColumn = (record) => {
        const $table = getXTable();
        $table.remove(record);
        record.isDispalyLine = false;
        VueEvent.emit('changeLine', record);
        getDisabled(record);
      };

      //获得列表对象
      const getXTable = () => {
        return xTable.value.$plugin;
      };

      //列表复选框值改变改变连线
      const changeCheckbox = (row) => {
        VueEvent.emit('changeLine', row);
        getDisabled(row);
      };

      //表A值改变需要吧对应的id,name赋值
      const selectTable1 = (row) => {
        const tableCode = row.mainTableCode;
        tableDesigndata.selectDatas.forEach((item) => {
          if (item.value == tableCode) {
            row.mainTableId = item.tableId;
            row.mainTableName = item.tableName;
          }
        });
        getDisabled(row);
      };

      //表B值改变需要吧对应的id,name赋值
      const selectTable2 = (row) => {
        const tableCode = row.targetTableCode;
        tableDesigndata.selectDatas.forEach((item) => {
          if (item.value == tableCode) {
            row.targetTableId = item.tableId;
            row.targetTableName = item.tableName;
          }
        });
        getDisabled(row);
      };

      //判断显示列是否只读
      const getDisabled = (row) => {
        if (row.mainTableId == '' || row.targetTableId == '') {
          return false;
        }
        const tableData = getXTable().getTableData().tableData;
        let slectRow = [];
        //循环先找到一致的数据
        tableData.forEach((record) => {
          if (
            ((row.mainTableId == record.mainTableId && row.targetTableId == record.targetTableId) ||
              (row.mainTableId == record.targetTableId &&
                row.targetTableId == record.mainTableId)) &&
            record.isDispalyLine
          ) {
            slectRow.push(record);
          }
        });

        tableData.forEach((record) => {
          if (
            (row.mainTableId == record.mainTableId && row.targetTableId == record.targetTableId) ||
            (row.mainTableId == record.targetTableId && row.targetTableId == record.mainTableId)
          ) {
            //如果有选中的数据
            if (slectRow.length > 0) {
              //选中的数据和当前的数据是同一条就可以编辑
              if (slectRow[0].id == record.id) {
                record.disabled = false;
              } else {
                //选中的数据和当前的数据不是同一条不可以编辑
                record.disabled = true;
              }
            } else {
              //没有选中的数据都可以编辑
              record.disabled = false;
            }
          }
        });
      };

      //级联删除关系设置的Table数据
      const deleteTableData = (tableId) => {
        const $table = getXTable();
        $table.getTableData().tableData.forEach((item, index) => {
          if (item.mainTableId == tableId || item.targetTableId == tableId) {
            $table.remove(item);
            getDisabled(item);
          }
        });
      };

      //监听设计视图的数据删除,级联删除数据
      VueEvent.on('deleteConcernTableData', (tableId) => {
        deleteTableData(tableId);
      });

      //分装j_query
      const getJQuery = (row, tableCode) => {
        const j_query = [
          { code: 'TABLECOLUMN_TABLECODE', type: '=', value: row[tableCode], cn: 'and' },
          { code: 'TABLECOLUMN_ISCREATE', type: '=', value: '1', cn: 'and' },
        ];
        return j_query;
      };

      //点击icon
      const visibleCondition = ref(false);
      const modalText = ref('');
      const clickIcon = (type) => {
        visibleCondition.value = true;
        switch (type) {
          case 'mainIdentifier': // 标识A
            modalText.value = '标识A表示表A与表B的数据映射关系。';
            break;
          case 'targetIdentifier': // 标识B
            modalText.value = '标识B表示表B与表A的数据映射关系。';
            break;
          case 'isDispalyLine': // 显示
            modalText.value = '勾选显示后，将在设计视图页面展示表A与表B的映射关系。';
            break;
        }
      };

      return {
        tableDesigndata,
        getSelectLabel,
        addColumn,
        xTable,
        getXTable,
        deleteColumn,
        changeCheckbox,
        selectTable1,
        selectTable2,
        getDisabled,
        inputRender,
        numberRender,
        getJQuery,
        visibleCondition,
        clickIcon,
        modalText,
      };
    },
  });
</script>

<style lang="less" scoped>
  .design-title {
    height: 40px;
    background: #f7f9fc;
    line-height: 40px;
    font-size: 14px;
    padding: 0 16px;
    color: #3265f5;
  }
  .design-title.bottom {
    //position: relative;
    border-top: 1px solid #e6e6e6;
    border-bottom: 1px solid #e6e6e6;
  }
  .design-table {
    height: 100%;
    .conditionicon {
      color: #ebebeb;
      cursor: pointer;
      margin-right: 5px;
      &:hover {
        color: #3265f5;
      }
    }
  }
</style>
